require([
    'jquery',
    'module/handlebars',
    'global',
    'underscore',
    'jquery.debounce',
    'jquery.scrollto',
    'requirejs/domready!'], 
function($, handlebars, g, _) {
	
	var modelId = $('#model-id-marker').data('id');
	var category = $('#category-marker').data('id');
	
	var resizeHandler = function(){
		$('.left-tree').css('height', $('.left-nav').height()-
				($('.alpha-box').css('display') != 'none' ? $('.alpha-box').height() : 0));
	};
	
	// window resize handler
	$(window).resize($.debounce( 250, resizeHandler));
	
	
	$('.left-nav').on('click', '.alpha-box .btn', function(){
		var alpha = $(this).text();
		$('.left-tree').scrollTo('#panel-'+alpha,400);
	});
	
	$('.left-nav').on('show.bs.collapse','.vb-panel', function(){
		$(this).find('.panel-heading i.fa').addClass('fa-minus-square-o').removeClass('fa-plus-square-o');
	}).on('hide.bs.collapse','.vb-panel', function(){
		$(this).find('.panel-heading i.fa').addClass('fa-plus-square-o').removeClass('fa-plus-minus-o');
	});
	
	$.when($.getJSON(g.context + '/vehicles'), 
			handlebars.getTemplate('brand-panels'))
		.done(function(data, tmpl){
			var d = data[0].data;
			var keys = _.keys(d), alphas=[], o;
			_.each(['A','B','C','D','E','F','G','H','I','J','K',
			        'L','M','N','O','P','Q','R','S','T','U','V',
			        'W','X','Y','Z'],
			    function(a){
					o = {
						lette: a,
						non: false
					};
					if(!_.contains(keys, a)){
						o.non = true;
					}
					alphas.push(o);
				});
			var html = tmpl({
					alphas: alphas, 
					vehicles: d, 
					context: g.context, 
					category: category||'cover'
				});
			$('.left-nav').append(html);
			resizeHandler();
			setTimeout(function(){
				if(modelId){
					var $vm = $('.left-nav .vm-item[data-id='+modelId+']');
					$vm.parents('.panel.vb-panel')
						.find('.panel-title a')
						.trigger('click');
					$vm.find('a').addClass('selected');
					var th = $('.left-tree').height();
					$('.left-tree').scrollTo($vm).scrollTo('-='+th/2+'px');
				}
			});
		});
	
	resizeHandler();
});